<template>
  <div class="register-container">
    <div class="register-box">
      <div class="register-logo">
        <a href="#">
          <img src="../../assets/logo.png" alt="logo">
        </a>
      </div>
      <div class="register-form">
        <h3>用户注册</h3>
        <el-form ref="form" :model="registerForm" :rules="rules" label-position="left" label-width="0">
          <el-form-item prop="username">
            <el-input v-model="registerForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input type="password" v-model="registerForm.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="do_register" :loading="loading1">提交</el-button>
            <el-button type="primary" @click="go_login" :loading="loading2">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
import {register} from '@/api/register.js'

export default {
  data() {
    return {
      registerForm: {
        username: '',
        password: '',
      },
      rules: {
        username: [{required: true, message: '请输入用户名', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
      },
      loading1: false,
      loading2: false
    }
  },
  methods: {
    do_register() {
      this.$refs.form.validate(valid => {
        if (valid) {
          //加载登录动画，登录中的圆圈会转起来
          this.loading1 = true
          //发起网络请求，登录，如果登录成功，跳转到主界面，特别注意4月11日这天后端接口发生了变化，不能生搬硬套上节课的接口！
          register(this.registerForm.username,
              this.registerForm.password).then(res => {
            // console.log(res)
            if (res.code === 50003) {
              this.$message.error(res.msg)
              this.loading1 = false
              //this.$router.push({path: '/register'})
              return
            }
            this.loading1 = false
            this.$message.success('注册成功')
            this.$router.push({path: '/login'})
          }).catch(() => {
            // 登录失败，显示错误提示
            this.$message.error('注册失败')
            this.loading = false
          })
        }
      })
    },
    go_login() {
      this.$router.push('/login');
      this.loading2 = true
    }

  }
}
</script>

<style lang="scss">
.register-container {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  .register-box {
    width: 400px;
    //height: 400px;
    border-radius: 5px;
    box-shadow: 0px 0px 10px #ccc;

    .register-logo {
      height: 100px;
      display: flex;
      justify-content: center;
      align-items: center;

      img {
        height: 80%;
      }
    }

    .register-form {
      padding: 20px;

      h3 {
        font-size: 24px;
        margin-bottom: 20px;
        text-align: center;
      }
    }
  }
}
</style>
